import { computed } from 'vue';
import type { Ref } from 'vue';
import { arr_push_ref, arr_splice_ref } from './functions';

export type FnConvert<T> = (t?: T) => T | undefined;

export interface ArrayProps<T> {
  /**
   * 元素-要数组化的元素
   */
  item?: T;
  /**
   * 方法-元素需要幻化一下
   */
  fnConvert?: FnConvert<T>;
  /**
   * 数值-新建的元素的默认值
   */
  create?: () => unknown;
}

export const useArray = <T>(
  modelValue: Ref<Array<unknown> | undefined>,
  props?: ArrayProps<T>,
) => {
  const item_ = computed(() => props?.fnConvert?.(props?.item) ?? props?.item);

  const add = () => arr_push_ref(modelValue, props?.create?.() ?? undefined);
  const remove = (index: number) => arr_splice_ref(modelValue, index, 1);
  const modify = (index: number, v: unknown) =>
    arr_splice_ref(modelValue, index, 1, v);

  return { item_, remove, add, modify };
};
